package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dao.GoodsFreeMapper;
import com.eco.fanliapp.dao.SyChannelGoodsMapper;
import com.eco.fanliapp.dao.SyTljGoodsfreeMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.GoodsFreeInfo;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.TbkPrivilegeGetInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class GoodsFreeServiceImpl extends ServiceImpl<GoodsFreeMapper, GoodsFree> implements IGoodsFreeService {

    private static final Logger log = LoggerFactory.getLogger(GoodsTopServiceImpl.class);

    @Autowired
    private GoodsFreeMapper goodsFreeMapper;

    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private FindItemIdUtils taoBaoUtils;

    @Autowired
    private IAppUserService userService;

    @Autowired
    private IAppUserOrderService appUserOrderService;

    @Autowired
    private ISySwitchService iSySwitchService;

    @Autowired
    private SyChannelGoodsMapper syChannelGoodsMapper;
    @Autowired
    private SyTljGoodsfreeMapper syTljGoodsfreeMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;

    private int invalidOrders = 0;
    private Double totalRetureAmount = 0.0;

//    public List<GoodsFree> getGoodsFree(int type){
//        String redisKeyStr = "app_goodsFree_list";
//        List<GoodsFree> goodsFrees = null;
//        if (type == 1 && redisTemplateService.hasKey(redisKeyStr)) {
//            goodsFrees = redisTemplateService.getTByListKey(redisKeyStr, GoodsFree.class);
//        }
//        if (goodsFrees == null || goodsFrees.size() <= 0) {
//            goodsFreeMapper.
//        }
//        return null;
//    }

    /**
     * 增加免单商品
     * 根据商品id
     *
     * @param goodsFreeInfo
     * @return
     */
    @Override
    public ServerResponse addGoodsFree(AppGoods appGoods, GoodsFreeInfo goodsFreeInfo) {

        GoodsFree goodsFree = new GoodsFree();
        goodsFree.setGoodsId(goodsFreeInfo.getGoodsId());
        goodsFree.setGoodsName(goodsFreeInfo.getGoodsName());
        goodsFree.setGoodsPlatform(goodsFreeInfo.getGoodsPlatform());
        goodsFree.setFixedAmount(goodsFreeInfo.getFixedAmount());
        Long longEndTime = DateFormatUtils.convertTimeToLong(goodsFreeInfo.getEndTime());
        goodsFree.setEndTime(longEndTime);
        // 需要更改逻辑
        Long longBeginTime = DateFormatUtils.dateToLong(new Date());
        goodsFree.setBeginTime(longBeginTime);
        goodsFree.setGoodsPictureUrl(appGoods.getItempic());
        goodsFree.setGoodsTitle(appGoods.getItemtitle());
        if (longEndTime > System.currentTimeMillis()) {
            goodsFree.setGoodsStatus(2);
        } else {
            goodsFree.setGoodsStatus(1);
        }
        // 计算佣金
        goodsFree.setInvalidOrders(invalidOrders);//没用
        // 计算总体佣金
        goodsFree.setTotalRetureAmount(totalRetureAmount);//没用
        GoodsFree goods = goodsFreeMapper.selectByGoodsId(goodsFree.getGoodsId());
        if (goods == null) {
            int insert = goodsFreeMapper.insert(goodsFree);
            if (insert == 1) {
                return ServerResponse.createBySuccessMessage("数据增加成功");
            }
            return ServerResponse.createByErrorMessage("数据增加失败");
        }
        int update = goodsFreeMapper.updateByGoodsIdSelective(goodsFree);
        if (update == 1) {
            return ServerResponse.createBySuccessMessage("数据修改成功");
        }

        return ServerResponse.createByErrorMessage("数据修改失败");
    }

    @Override
    public ServerResponse updateByGoodsFree(GoodsFree goodsFree) {
        long time = System.currentTimeMillis();
        int i = goodsFreeMapper.updateByGoodsFree(goodsFree);
        String redisKeyStr = "app_goodsFree_goods_" + goodsFree.getGoodsId();
        redisTemplateService.del(redisKeyStr);
        AppGoods appGoods = new AppGoods();
        appGoods.setItemid(goodsFree.getGoodsId());
        appGoods.setTkmoney(String.valueOf(goodsFree.getFixedAmount()));
        appGoods.setItempic(goodsFree.getPrintUrl());
        appGoods.setItemtitle(goodsFree.getGoodsName());
        appGoods.setItemshorttitle(goodsFree.getGoodsName());
        if (i > 0) {
            //查询商品表中是否存在该商品 如果不存在就添加存在就修改
            List<AppGoods> appGoods1 = appGoodsMapper.selectAppGoodsByItemId(Long.valueOf(goodsFree.getGoodsId()));
            if (appGoods1.size() > 0) {
                if (time > Long.valueOf(appGoods1.get(0).getEndTime())) {
                    appGoodsMapper.updateTkmoney(appGoods);
                    return ServerResponse.createBySuccessMessage("修改成功");
                } else {
                    return ServerResponse.createByErrorMessage("修改失败");
                }
            } else {
                HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(appGoods.getItemid());
                if (info != null && info.getCode() == 1 && info.getData() != null) {
                    AppGoods goods = HDKUtils.getAppGoodsFromHDK(info.getData());
                    goods.setTkmoney(String.valueOf(goodsFree.getFixedAmount()));
                    goods.setItemTop(3);
                    goods.setFqcat("0");
                    goods.setItempic(goodsFree.getPrintUrl());
                    goods.setItemtitle(goodsFree.getGoodsName());
                    goods.setItemshorttitle(goodsFree.getGoodsName());
                    goods.setCreateTime(DateUtils.getNowTimestamp());
                    goods.setUpdateTime(DateUtils.getNowTimestamp());
                    int i2 = appGoodsMapper.insertAppGoods(goods);
                    if (i2 > 0) {
                        return ServerResponse.createBySuccessMessage("修改成功");
                    } else {
                        return ServerResponse.createByErrorMessage("修改失败");
                    }
                } else {
                    //查询淘宝详情
                    List<TbkItemInfoGetInfo.NTbkItem> items = taoBaoUtils.getTaoBaoItemId(appGoods.getItemid());
                    if (items != null && items.size() > 0) {
                        for (TbkItemInfoGetInfo.NTbkItem nTbkItem : items) {
                            AppGoods goods2 = HDKUtils.getAppGoodsFromTB(nTbkItem);
                            goods2.setItemTop(3);
                            goods2.setFqcat("0");
                            TbkPrivilegeGetInfo.TbkPrivilege privilege = taoBaoUtils.getPrivilegeItemId(Long.valueOf(goods2.getItemid()));
                            goods2.setCouponmoney(Double.valueOf(privilege.getCouponInfo()));
                            goods2.setCouponstarttime(privilege.getCouponStartTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponStartTime()).toString());
                            goods2.setCouponendtime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
                            goods2.setEndTime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
                            BigDecimal itemendprice = BigDecimalUtils.Format(
                                    new BigDecimal(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
                                            .subtract(new BigDecimal(privilege.getCouponInfo()))
                            );
                            goods2.setItemendprice(itemendprice.doubleValue());
                            goods2.setTkrates(privilege.getMaxCommissionRate());
                            goods2.setItemprice(nTbkItem.getZkFinalPrice().toString());
                            goods2.setTkmoney(String.valueOf(goodsFree.getFixedAmount()));

                            goods2.setItempic(goodsFree.getPrintUrl());
                            goods2.setItemtitle(goodsFree.getGoodsName());
                            goods2.setItemshorttitle(goodsFree.getGoodsName());
                            goods2.setCreateTime(DateUtils.getNowTimestamp());
                            goods2.setUpdateTime(DateUtils.getNowTimestamp());
                            int i2 = appGoodsMapper.insertAppGoods(goods2);
                            if (i2 > 0) {
                                return ServerResponse.createBySuccessMessage("修改成功");
                            } else {
                                return ServerResponse.createByErrorMessage("修改失败");
                            }
                        }
                    } else {
                        return ServerResponse.createByErrorMessage("未搜索到该商品");
                    }
                }
                return ServerResponse.createByErrorMessage("修改失败");
            }
        } else {
            return ServerResponse.createByErrorMessage("修改失败");
        }
    }

    @Override
    public GoodsFree selectByGoodsId(String goodsId) {
        return goodsFreeMapper.selectByGoodsId(goodsId);
    }

    /**
     * 淘宝商品详情添加
     *
     * @param goodsFreeInfo
     * @return
     */
    @Override
    public ServerResponse addGoodsFreeByTaoBao(GoodsFree goodsFreeInfo) {
        //默认总公司
        goodsFreeInfo.setCompanyId(1);
        //默认平台淘宝
        goodsFreeInfo.setGoodsPlatform(1);
        if (!RegUtils.isNumeric(goodsFreeInfo.getGoodsId())) {
            return ServerResponse.createByErrorMessage("商品id格式不正确");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("goodsId", goodsFreeInfo.getGoodsId());
        map.put("companyId", goodsFreeInfo.getCompanyId());
        map.put("goodsStatus", 2);
        int size = goodsFreeMapper.selectByGoodsIds(map).size();
        if (size > 0) {
            return ServerResponse.createByErrorMessage("该商品已经存在(且为激活状态)，请选择其他它商品");
        }
        //判断商品是否存在淘礼金,高佣中
        SyChannelGoods syChannelGoods = syChannelGoodsMapper.selectChannelGoodsById(Long.valueOf(goodsFreeInfo.getGoodsId()));
        SyTljGoodsfree syTljGoodsfree = syTljGoodsfreeMapper.selectTljGoodsfreeByItemId(Long.valueOf(goodsFreeInfo.getGoodsId()));
        if (syTljGoodsfree != null && DateUtils.date2Strday(syTljGoodsfree.getUpdateTime()).equals(DateUtils.date2Strday(new Date())) || syChannelGoods!=null) {
            return ServerResponse.createByErrorMessage("商品已经在淘礼金或高佣中存在");
        }
//        if (syTljGoodsfree == null && syChannelGoods == null) {
            AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(goodsFreeInfo.getGoodsId());
            if (appGoods != null) {
                GoodsFree goodsFree = new GoodsFree();
                goodsFree.setGoodsId(goodsFreeInfo.getGoodsId());
                goodsFree.setGoodsName(goodsFreeInfo.getGoodsName() == null ? appGoods.getItemshorttitle() : goodsFreeInfo.getGoodsName());
                goodsFree.setGoodsPlatform(goodsFreeInfo.getGoodsPlatform());
                goodsFree.setFixedAmount(goodsFreeInfo.getFixedAmount());
                Long longEndTime = goodsFreeInfo.getEndTime();
                goodsFree.setEndTime(longEndTime);
                Long longBeginTime = DateFormatUtils.dateToLong(new Date());
                goodsFree.setBeginTime(longBeginTime);
                goodsFree.setGoodsPictureUrl(appGoods.getItempic());
                goodsFree.setGoodsTitle(appGoods.getItemtitle());
                if (longEndTime > System.currentTimeMillis()) {
                    goodsFree.setGoodsStatus(2);
                } else {
                    goodsFree.setGoodsStatus(1);
                }
                goodsFree.setPrintUrl(goodsFreeInfo.getPrintUrl() == null ? appGoods.getItempic() : goodsFreeInfo.getPrintUrl());
                goodsFree.setNumber(goodsFreeInfo.getNumber());
                goodsFree.setCompanyId(goodsFreeInfo.getCompanyId());
                int insert = goodsFreeMapper.insertSelective(goodsFree);
                String redisKeyStr = "app_goodsFree_goods_" + goodsFree.getGoodsId();
                redisTemplateService.del(redisKeyStr);
                appGoods.setItemTop(3);
                appGoods.setFqcat("0");
                appGoods.setTkmoney(String.valueOf(goodsFreeInfo.getFixedAmount()));
                appGoods.setItempic(goodsFreeInfo.getPrintUrl());
                appGoods.setItemtitle(goodsFreeInfo.getGoodsName());
                appGoods.setItemshorttitle(goodsFreeInfo.getGoodsName());
                appGoodsMapper.updateAppGoods(appGoods);
                if (insert == 1) {
                    return ServerResponse.createBySuccessMessage("数据增加成功");
                } else {
                    return ServerResponse.createByErrorMessage("数据增加失败");
                }
            } else {
                //如果不存在查好单库
                HaoDanKuItemInfo info = taoBaoUtils.getHaoDanKuItemId(goodsFreeInfo.getGoodsId());
                if (info != null && info.getCode() == 1 && info.getData() != null) {
                    GoodsFree goodsFree = new GoodsFree();
                    goodsFree.setGoodsId(goodsFreeInfo.getGoodsId());
                    goodsFree.setGoodsName(goodsFreeInfo.getGoodsName() == null ? info.getData().getItemshorttitle() : goodsFreeInfo.getGoodsName());
                    goodsFree.setGoodsPlatform(goodsFreeInfo.getGoodsPlatform());
                    goodsFree.setFixedAmount(goodsFreeInfo.getFixedAmount() == null ? Double.valueOf(info.getData().getItemendprice() == null ? "0" : info.getData().getItemendprice()) : goodsFreeInfo.getFixedAmount());
                    Long longEndTime = goodsFreeInfo.getEndTime();
                    goodsFree.setEndTime(longEndTime);
                    Long longBeginTime = DateFormatUtils.dateToLong(new Date());
                    goodsFree.setBeginTime(longBeginTime);
                    goodsFree.setGoodsPictureUrl(info.getData().getItempic());
                    goodsFree.setGoodsTitle(info.getData().getItemtitle());
                    if (longEndTime > System.currentTimeMillis()) {
                        goodsFree.setGoodsStatus(2);
                    } else {
                        goodsFree.setGoodsStatus(1);
                    }
                    goodsFree.setPrintUrl(goodsFreeInfo.getPrintUrl() == null ? info.getData().getItempic() : goodsFreeInfo.getPrintUrl());
                    goodsFree.setNumber(goodsFreeInfo.getNumber());
                    goodsFree.setCompanyId(goodsFreeInfo.getCompanyId());
                    int i = goodsFreeMapper.insertSelective(goodsFree);
                    if (i > 0) {
                        String redisKeyStr = "app_goodsFree_goods_" + goodsFree.getGoodsId();
                        redisTemplateService.del(redisKeyStr);
                        AppGoods goods = HDKUtils.getAppGoodsFromHDK(info.getData());
                        if (!StringUtils.isEmpty(goodsFreeInfo.getFixedAmount())) {
                            goods.setTkmoney(String.valueOf(goodsFreeInfo.getFixedAmount()));
                        }
                        goods.setItemTop(3);
                        goods.setFqcat("0");
                        if (!StringUtils.isEmpty(goodsFreeInfo.getPrintUrl())) {
                            goods.setItempic(goodsFreeInfo.getPrintUrl());
                        }
                        if (!StringUtils.isEmpty(goodsFreeInfo.getGoodsName())) {
                            goods.setItemtitle(goodsFreeInfo.getGoodsName());
                            goods.setItemshorttitle(goodsFreeInfo.getGoodsName());
                        }
                        int i2 = appGoodsMapper.insertAppGoods(goods);
                        if (i2 > 0) {
                            return ServerResponse.createBySuccessMessage("添加成功");
                        } else {
                            return ServerResponse.createByErrorMessage("添加失败");
                        }
                    } else {
                        return ServerResponse.createByErrorMessage("添加失败");
                    }
                } else {
                    //查询淘宝详情
                    List<TbkItemInfoGetInfo.NTbkItem> items = taoBaoUtils.getTaoBaoItemId(goodsFreeInfo.getGoodsId());
                    if (items != null && items.size() > 0) {
                        for (TbkItemInfoGetInfo.NTbkItem nTbkItem : items) {
                            GoodsFree goodsFree = new GoodsFree();

                            goodsFree.setGoodsId(goodsFreeInfo.getGoodsId());
                            goodsFree.setGoodsName(goodsFreeInfo.getGoodsName() == null ? nTbkItem.getTitle() : goodsFreeInfo.getGoodsName());
                            goodsFree.setGoodsPlatform(goodsFreeInfo.getGoodsPlatform());
                            goodsFree.setFixedAmount(goodsFreeInfo.getFixedAmount());
                            Long longEndTime = goodsFreeInfo.getEndTime();
                            goodsFree.setEndTime(longEndTime);
                            Long longBeginTime = DateFormatUtils.dateToLong(new Date());
                            goodsFree.setBeginTime(longBeginTime);
                            goodsFree.setGoodsPictureUrl(nTbkItem.getPictUrl());
                            goodsFree.setGoodsTitle(nTbkItem.getTitle());
                            if (longEndTime > System.currentTimeMillis()) {
                                goodsFree.setGoodsStatus(2);
                            } else {
                                goodsFree.setGoodsStatus(1);
                            }
                            goodsFree.setPrintUrl(goodsFreeInfo.getPrintUrl() == null ? nTbkItem.getPictUrl() : goodsFreeInfo.getPrintUrl());
                            goodsFree.setNumber(goodsFreeInfo.getNumber());
                            goodsFree.setCompanyId(goodsFreeInfo.getCompanyId());
                            int i = goodsFreeMapper.insertSelective(goodsFree);
                            if (i > 0) {
                                String redisKeyStr = "app_goodsFree_goods_" + goodsFree.getGoodsId();
                                redisTemplateService.del(redisKeyStr);
                                AppGoods goods2 = HDKUtils.getAppGoodsFromTB(nTbkItem);
                                goods2.setItemTop(3);
                                goods2.setFqcat("0");
                                TbkPrivilegeGetInfo.TbkPrivilege privilege = taoBaoUtils.getPrivilegeItemId(Long.valueOf(goods2.getItemid()));
                                goods2.setCouponmoney(Double.valueOf(privilege.getCouponInfo()));
                                goods2.setCouponstarttime(privilege.getCouponStartTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponStartTime()).toString());
                                goods2.setCouponendtime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
                                goods2.setEndTime(privilege.getCouponEndTime() == null ? "0" : DateFormatUtils.dateToStamp(privilege.getCouponEndTime()).toString());
                                BigDecimal itemendprice = BigDecimalUtils.Format(
                                        new BigDecimal(nTbkItem.getZkFinalPrice() == null ? "0" : nTbkItem.getZkFinalPrice())
                                                .subtract(new BigDecimal(privilege.getCouponInfo()))
                                );
                                goods2.setItemendprice(itemendprice.doubleValue());
                                goods2.setTkrates(privilege.getMaxCommissionRate());
                                goods2.setItemprice(nTbkItem.getZkFinalPrice().toString());
                                if (!StringUtils.isEmpty(goodsFreeInfo.getFixedAmount())) {
                                    goods2.setTkmoney(String.valueOf(goodsFreeInfo.getFixedAmount()));
                                }
                                if (!StringUtils.isEmpty(goodsFreeInfo.getPrintUrl())) {
                                    goods2.setItempic(goodsFreeInfo.getPrintUrl());
                                }

                                if (!StringUtils.isEmpty(goodsFreeInfo.getGoodsName())) {
                                    goods2.setItemtitle(goodsFreeInfo.getGoodsName());
                                    goods2.setItemshorttitle(goodsFreeInfo.getGoodsName());
                                }
                                goods2.setCreateTime(DateUtils.getNowTimestamp());
                                goods2.setUpdateTime(DateUtils.getNowTimestamp());
                                int i2 = appGoodsMapper.insertAppGoods(goods2);
                                if (i2 > 0) {
                                    return ServerResponse.createBySuccessMessage("商品添加成功");
                                } else {
                                    return ServerResponse.createByErrorMessage("商品添加失败");
                                }
                            } else {
                                return ServerResponse.createByErrorMessage("商品添加失败");
                            }
                        }
                    }
                    return ServerResponse.createByErrorMessage("商品不存在");
                }
            }
//        }
//        return ServerResponse.createByErrorMessage("商品已经在淘礼金或高佣中存在");
    }

    /**
     * 查询所有免单商品
     *
     * @return
     */
    @Override
    public ServerResponse<PageInfo> findAll(Integer companyId, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("companyId", companyId);
        List goodsFrees = goodsFreeMapper.findAll(hashMap);
        if (goodsFrees == null) {
            return ServerResponse.createByErrorMessage("查询失败");
        }
        return ServerResponse.createBySuccess("查询成功", new PageInfo(goodsFrees));
    }

    /**
     * 根据平台查询免单商品
     *
     * @param platform
     * @return
     */
    @Override
    public ServerResponse<List> selectByPlatform(Integer platform) {
        List<GoodsFree> goodsFreeList = goodsFreeMapper.selectByGoodsPlatform(platform);
        return ServerResponse.createBySuccess("数据查询成功", goodsFreeList);
    }

    /**
     * 根据商品Id删除数据库的记录,goods_free
     *
     * @param id
     */
    @Override
    public ServerResponse deleteByGoodsId(Integer id) {
       /* GoodsFree goodsFree = this.getById(id);
        if(StringUtils.isEmpty(goodsFree))return ServerResponse.createByErrorMessage("商品不存在");*/
       /* if (deleteNum > 0) {
       int i = appGoodsMapper.deleteByGoodsId(Long.valueOf(goodsFree.getId()));*/
        int deleteNum = goodsFreeMapper.deleteByGoodsId(id);
        if (deleteNum > 0) {
            String redisKeyStr = "app_goodsFree_goods_" + id;
            redisTemplateService.del(redisKeyStr);
            return ServerResponse.createBySuccessMessage("数据删除成功");
        }
        return ServerResponse.createByErrorMessage("数据删除不成功");
    }

    /**
     * 动态字段,根据商品Id来更新符合条件的数据库记录,goods_free
     *
     * @param record
     */
    @Override
    public ServerResponse updateByGoodsIdSelective(GoodsFree record) {

        int updateNum = goodsFreeMapper.updateByGoodsIdSelective(record);
        if (updateNum == 1) {
            return ServerResponse.createBySuccessMessage("数据修改成功");
        }
        return ServerResponse.createByErrorMessage("数据修改失败");
    }

    @Override
    public ServerResponse<List> selectByGoodsIdOrGoodsName(String goodsIdOrGoodsName) {

        List<GoodsFree> goodsFreeList = goodsFreeMapper.selectByGoodsIdOrGoodsName(goodsIdOrGoodsName);

        return ServerResponse.createBySuccess("数据查询成功", goodsFreeList);
    }

    /**
     * 根据平台或者关键字查询
     *
     * @param goodsPlatform
     * @param keyWord
     * @return
     */
    @Override
    public ServerResponse<PageInfo> selectByKeyWord(Integer companyId, Integer goodsPlatform, String keyWord, Integer currentPage, Integer pageSize) {

        PageHelper.startPage(currentPage, pageSize);
        // PageInfo pageInfo = new PageInfo();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("companyId", companyId);
        hashMap.put("goodsPlatform", goodsPlatform);
        hashMap.put("keyWord", keyWord);
        List goodsFrees = goodsFreeMapper.findAll(hashMap);
        if (goodsFrees == null) {
            return ServerResponse.createByErrorMessage("查询失败");
        }
        return ServerResponse.createBySuccess("查询成功", new PageInfo(goodsFrees));
    }

    @Override
    public ServerResponse<PageInfo> updateGoodsFreeStageByGoodsId(String goodsId, Integer goodsFreeStage) {

        GoodsFree goodsFree = goodsFreeMapper.selectByGoodsId(goodsId);
        Integer topStage = goodsFree.getGoodsFreeStage();
        // 判断数据库中的商品是否置顶
        if (topStage == 3) {
            return ServerResponse.createBySuccessMessage("商品已免单");
        }
        int updateNum = goodsFreeMapper.updateGoodsFreeStageByGoodsId(goodsId, goodsFreeStage);
        if (updateNum == 1) {
            int stageNum = appGoodsMapper.updateGoodsTopStageByGoodsId(goodsId, goodsFreeStage);
            if (stageNum == 1) {
                return ServerResponse.createBySuccessMessage("修改免单状态成功");
            }
            return ServerResponse.createByErrorMessage("修改免单状态不成功");
        }
        return ServerResponse.createByErrorMessage("修改免单状态不成功");
    }


    @Override
    public GoodsFree selectByGoodsId(Long numIid) {
        // TODO Auto-generated method stub
        Integer goodsStatus = 2;//商品状态（2，已激活；1，已过期）
        Integer goodsFreeStage = 3;//商品免单状态（1不免单3免单）
        return goodsFreeMapper.findGoodsId(numIid, goodsStatus, null);
    }

    @Override
    public GoodsFree selectByGoodsIdAll(Long numIid) {
        return goodsFreeMapper.findGoodsIdAll(numIid);
    }

    @Override
    public int updateTotalOrdersByGoodsId(Integer id) {
        // TODO Auto-generated method stub
        return goodsFreeMapper.updateTotalOrdersByGoodsId(id);
    }

    @Override
    public int updateInvalidOrdersByGoodsId(Integer id) {
        // TODO Auto-generated method stub
        return goodsFreeMapper.updateInvalidOrdersByGoodsId(id);
    }

    @Override
    public int updateTotalRetureAmountByGoodsId(Integer id) {
        // TODO Auto-generated method stub
        return goodsFreeMapper.updateTotalRetureAmountByGoodsId(id);
    }

    @Override
    public ServerResponse updateSerial(HashMap<String, Object> hashMap) {
        MapValueHelper mapValueHelper = new MapValueHelper(hashMap);
        int freeSerialNumber = mapValueHelper.getInt("freeSerialNumber");
        int size = goodsFreeMapper.findFreeSerialMax(freeSerialNumber).size();
        if (size > 0) {
            return ServerResponse.createByErrorMessage("序号重复，请重新输入");
        } else {
            int i = goodsFreeMapper.updateSerial(hashMap);
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("保存成功");
            }
            return ServerResponse.createByErrorMessage("修改失败");
        }
    }

    /**
     * 查询免单商品（商品未失效）
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public ServerResponse<PageInfo> selectAllGoodsFree(Integer currentPage, Integer pageSize) {

        PageHelper.startPage(currentPage, pageSize);
        // PageInfo pageInfo = new PageInfo();
        List<GoodsFree> goodsFrees = goodsFreeMapper.selectAllGoodsFree();
        if (goodsFrees == null) {
            return ServerResponse.createByErrorMessage("查询失败");
        }
        long time = System.currentTimeMillis();
//        List<String> itemIds = new ArrayList<>();
//        List<AppGoods> appGoodsList = new ArrayList<>();
//        if (goodsFrees.size() > 0) {
//            for (GoodsFree goodsFree : goodsFrees) {
//                itemIds.add(goodsFree.getGoodsId());
//                QueryWrapper<AppGoods> queryWrapper = new QueryWrapper();
//                queryWrapper.in("itemid", itemIds);
//                appGoodsList = appGoodsMapper.selectList(queryWrapper);
//            }
//            if (appGoodsList == null) {
//                appGoodsList = new ArrayList<>();
//            }
//        }

        for (GoodsFree goodsFree : goodsFrees) {
            if (goodsFree.getGoodsStatus() == 1 || goodsFree.getEndTime() <= time || goodsFree.getTotalOrders() >= goodsFree.getNumber()) {
                goodsFree.setIfLootAll(1);
            }
            String redisKeyStr = "app_goodsFree_goods_" + goodsFree.getGoodsId();
            AppGoods appGoods = null;
            if (redisTemplateService.hasKey(redisKeyStr)) {
                appGoods = redisTemplateService.getTByKey(redisKeyStr, AppGoods.class);
            }
            if (appGoods == null) {
                appGoods = appGoodsMapper.findAppGoodsByItemId(goodsFree.getGoodsId());
                if (appGoods != null) {
                    redisTemplateService.set(redisKeyStr, appGoods, 60 * 5);
                }
            }
            if (appGoods != null) {
                goodsFree.setItemPrice(appGoods.getItemprice());
                //免单已抢数量
                goodsFree.setTotalOrders(appGoods.getItemsale());
            }
        }
        return ServerResponse.createBySuccess("查询成功", new PageInfo(goodsFrees));
    }

    @Override
    public int updateGoodsStausByGoodsFree(GoodsFree goodsFree) {
        return goodsFreeMapper.updateGoodsStausByGoodsFree(goodsFree);
    }

    @Override
    public ServerResponse<String> checkHaveBuy(Long userId, Integer isTaskUse) {
        AppUser appUser = userService.selectAppUserByUserId(userId, 0);

        if (appUser == null) {
            return ServerResponse.createBySuccessCodeMessage(301, "用户不存在");
        }
        if (appUser.getUserTaobaoAuthorization() == null || appUser.getUserTaobaoAuthorization() != 2 || appUser.getTaobaoUserId() == null || appUser.getTaobaoUserId() == 0) {
            return ServerResponse.createBySuccessCodeMessage(515, "未授权，无法购买免单");
        }


//        List<AppUser> appUsers = userService.selectAppUserListByUnionId(appUser);
//
//        List<Long> userIds = new ArrayList<>();
//        for (AppUser appUser_ : appUsers) {
//            userIds.add(appUser_.getUserId());
//        }

        int count = appUserOrderService.buyFreeNumByAllId(appUser.getTaobaoUserId());

        if (count <= 0) {
            return ServerResponse.createBySuccessCodeMessage(515, "用户可以购买免单商品");
        }

        return ServerResponse.createBySuccessCodeMessage(516, "您已经领过免单了，请把机会留给其他新人吧");
    }

    @Override
    public ServerResponse backRemind(Long userId) {
        HashMap map = new HashMap();
        Boolean popUp = true;
        SySwitch sySwitch = iSySwitchService.getById(10);
        ServerResponse response = checkHaveBuy(userId, null);

        if (sySwitch != null && sySwitch.getState() == 1) {
            //免单商品列表
            if (response.getStatus() == 515) {
                popUp = true;
            } else if (response.getStatus() == 516) {
                popUp = false;
            } else {
                return ServerResponse.createBySuccess(301, "用户不存在", map);
            }
        } else if (sySwitch != null && sySwitch.getState() == 0) {
            popUp = false;
        }
        List<GoodsFree> freeList = goodsFreeMapper.selectGoodsFreeValidList();
        if (freeList == null || freeList.size() != 2) {
            popUp = false;
        }

        for (GoodsFree goodsFree : freeList) {
            goodsFree.setFanlihoMoney(goodsFree.getItemPrice());
            AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(goodsFree.getGoodsId());
            //免单已抢数量
            if (appGoods != null) {
                goodsFree.setTotalOrders(appGoods.getItemsale());
            }

        }
        map.put("popUp", popUp);
        map.put("freeList", freeList);
        return ServerResponse.createBySuccess("查询成功", map);
    }

}
